package com.niiwoo.civet.trade.service.local.kaola;


import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.trade.dto.kaola.NotifyRepaymentResult;
import com.niiwoo.civet.trade.dto.kaola.Result;
import com.niiwoo.civet.trade.dto.response.kaola.KaoLaLiCaiReceiveDTO;
import com.niiwoo.civet.trade.enums.kaola.ErrorCodeConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 还款回调处理.
 * Created by daizhiyue on 2017/12/25.
 */
@Service("kaoLaLiCaiNotifyRepaymentService")
@Slf4j
public class KaoLaLiCaiNotifyRepaymentServiceImpl implements KaoLaLiCaiReceiveService{
    @Autowired
    private KaoLaLiCaiApplyService kaoLaLiCaiApplyService;

    @Override
    public KaoLaLiCaiReceiveDTO doService(Map<String, Object> bizDataMap) {
        Result result = null;
        NotifyRepaymentResult notifyRepaymentResult = null;
        String bizDataJSONStr = JSON.toJSONString(bizDataMap);
        log.info("kaoLaLiCaiNotifyRepaymentService param:{}",bizDataJSONStr);

        try{
            notifyRepaymentResult = JSON.parseObject(bizDataJSONStr,NotifyRepaymentResult.class);
        }catch(Exception e){
            log.error("kaoLaLiCaiNotifyRepaymentService jsonexception",e);
            return new KaoLaLiCaiReceiveDTO(ErrorCodeConstants.PARAM_FORMAT_ERROR, ErrorCodeConstants.PARAM_FORMAT_ERROR_MSG);
        }

        try{
            result = kaoLaLiCaiApplyService.notifyRepayment(notifyRepaymentResult);
        }catch(Exception e){
            log.error("kaoLaLiCaiNotifyRepaymentService exception",e);
            return new KaoLaLiCaiReceiveDTO(ErrorCodeConstants.KAOLALICAI_NOTIFY_REPAYMENT_EXCEPTION,ErrorCodeConstants.KAOLALICAI_NOTIFY_REPAYMENT_EXCEPTION_MSG);
        }

        if(!result.isSuccess()){
            return new KaoLaLiCaiReceiveDTO(ErrorCodeConstants.KAOLALICAI_NOTIFY_REPAYMENT_EXCEPTION,result.getMessage());
        }
        return new KaoLaLiCaiReceiveDTO(KaoLaLiCaiReceiveDTO.SUCCESS_CODE);
    }
}
